package com.gopay.common.metric;

import com.gopay.common.util.UUIDUtils;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * JVM 指标
 * Created by xuHui on 2017/6/28.
 */
public class JVMMetricSource implements MetricSource{

    private Map<String, String> tags;

    @Override
    public void record(String url){
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();

        boolean needJudge = true;
        Date current = new Date();
        Metric metric = new Metric();
        List<Metric> metrics = new ArrayList<>();


        metric.setId(UUIDUtils.getId());
        metric.setMetric(MetricNameConst.JVM_MEMORY_HEAP_USAGE_SIZE);
        metric.setTags(tags);
        metric.setValue(heapMemoryUsage.getUsed() / 1024.0 / 1024);
        metric.setTime(current);
        metric.setNeedJudge(needJudge);
        metrics.add(metric);

        metric = new Metric();
        metric.setId(UUIDUtils.getId());
        metric.setMetric(MetricNameConst.JVM_MEMORY_HEAP_USAGE_PERCENT);
        metric.setTags(tags);
        metric.setValue((double) heapMemoryUsage.getUsed() / heapMemoryUsage.getMax() * 100);
        metric.setTime(current);
        metric.setNeedJudge(needJudge);
        metrics.add(metric);

        MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();

        metric = new Metric();
        metric.setId(UUIDUtils.getId());
        metric.setMetric(MetricNameConst.JVM_MEMORY_NONHEAP_USAGE_SIZE);
        metric.setTags(tags);
        metric.setValue(nonHeapMemoryUsage.getUsed() / 1024.0 / 1024);
        metric.setTime(current);
        metric.setNeedJudge(needJudge);
        metrics.add(metric);

        metric = new Metric();
        metric.setId(UUIDUtils.getId());
        metric.setMetric(MetricNameConst.JVM_MEMORY_NONHEAP_USAGE_PERCENT);
        metric.setTags(tags);
        metric.setValue((double) nonHeapMemoryUsage.getUsed() / nonHeapMemoryUsage.getMax() * 100);
        metric.setTime(current);
        metric.setNeedJudge(needJudge);
        metrics.add(metric);


        Client.record(metrics, url);

    }

    public Map<String, String> getTags() {
        return tags;
    }

    public void setTags(Map<String, String> tags) {
        this.tags = tags;
    }
}
